/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.berlin.jsf.util;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import ru.ssau.berlin.jsf.beans.NavigationController;

/**
 *
 * @author Caesar
 */
public class FacesApplication {

    private static FacesApplication instance;

    private Context context;
    private NavigationController navigator = new NavigationController();

    private FacesApplication() {
        try {
            context = new InitialContext();
        } catch (NamingException ex) {
            Logger.getLogger(FacesApplication.class.getName()).log(Level.SEVERE, null, ex);
            addErrorMessage(ex);
        }
    }

    public static FacesApplication getInstance() {
        if (instance == null) {
            synchronized (FacesApplication.class) {
                if (instance == null) {
                    instance = new FacesApplication();
                }
            }
        }
        return instance;
    }

    public void addErrorMessage(String msg) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg));
    }

    public void addErrorMessage(Exception ex) {
        addErrorMessage(ex.getLocalizedMessage());
    }

    public void addErrorMessage(Exception ex, String details) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR,
                ex.getLocalizedMessage(), details));
    }

    public Context getContext() {
        return context;
    }

    public NavigationController getNavigator() {
        return navigator;
    }

    public String getRequestParameter(String name) {
        Object param = FacesContext.getCurrentInstance().getExternalContext()
                .getRequestParameterMap().get(name);
        return param == null ? null : param.toString();
    }
    
}
